package cn.itsource.basic.util.job;

import cn.itsource.order.domain.OrderAdopt;
import cn.itsource.order.mapper.OrderAdoptMapper;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时任务执行类
 *
 * @author wangcp
 * @date 2021/05/10 10:42
 * //synchronized
 **/
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private OrderAdoptMapper orderAdoptMapper;


    @Async("taskExecutor")
    @Override
    public void executeRemindMessage() throws InterruptedException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前运行线的程名称：" + Thread.currentThread().getName() + " ,执行定时任务了,执行时间为：" + sdf.format(date));
        Thread.sleep(1500);
    }

    /**
     * 超时关单
     * 需求:超过30分钟未支付的订单,通过任务关闭
     */
    @Async("taskExecutor")
    @Override
    public void timeOutCloseOrder() {
        //1.拿到订单,where条件  state = 0 订单时间时间 <= 半小时之前的时间
        String thirtyMinBefore = getMinuteAgoTime();

        List<OrderAdopt> orderAdopts = orderAdoptMapper.timeOutCloseOrder(thirtyMinBefore);

        //2.修改状态
        orderAdopts.forEach(orderAdopt -> {
            orderAdopt.setState(2);//已取消
            orderAdoptMapper.updateByPrimaryKeySelective(orderAdopt);
        });


        //System.out.println(JSONObject.toJSONString(orderAdopts));


    }

    public static String getMinuteAgoTime() {
        Date date = new Date();//获取当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, -30);// 30分钟前
        //获取到完整的时间
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
    }

    public static void main(String[] args) {
        System.out.println(getMinuteAgoTime());
    }
}